<template>
  <div>
    <el-form ref="formRef" :model="formData" label-width="120px">
      <el-form-item label="仓库ID" prop="warehouse_id" :error="errors.warehouse_id">
        <el-input v-model="formData.warehouse_id" type="number"></el-input>
      </el-form-item>
      <el-form-item label="物品ID" prop="item_id" :error="errors.item_id">
        <el-input v-model="formData.item_id" type="number"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="quantity" :error="errors.quantity">
        <el-input v-model="formData.quantity" type="number"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status" :error="errors.status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option label="PENDING" value="PENDING"></el-option>
          <el-option label="APPROVED" value="APPROVED"></el-option>
          <el-option label="REJECTED" value="REJECTED"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建者ID" prop="created_by" :error="errors.created_by">
        <el-input v-model="formData.created_by" type="number"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addInventory} from '@/api/inventory';

// 定义响应式数据
const formRef = ref(null);
const formData = reactive({
  warehouse_id: '',
  item_id: '',
  quantity: '',
  status: '',
  created_by: '',
});

const errors = reactive({
  warehouse_id: '',
  item_id: '',
  quantity: '',
  status: '',
  created_by: '',
});

// 校验表单
const validate = () => {
  errors.warehouse_id = formData.warehouse_id ? '' : '仓库ID不能为空';
  errors.item_id = formData.item_id ? '' : '物品ID不能为空';
  errors.quantity = formData.quantity ? '' : '数量不能为空';
  errors.status = formData.status ? '' : '状态不能为空';
  errors.created_by = formData.created_by ? '' : '创建者ID不能为空';
  return !Object.values(errors).some(error => error);
};

// 提交表单
const handleSubmit = async () => {
  if (!validate()) {
    ElMessage.error('请检查表单填写');
    return;
  }

  try {
    console.log('formData',formData);
    const response = await addInventory(formData);
    ElMessage.success(response.message);
    formRef.value.resetFields();
  } catch (error) {
    ElMessage.error(error.message || '添加库存失败');
  }
};

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  Object.keys(errors).forEach(key => errors[key] = '');
};

// 生命周期钩子
onMounted(() => {
  // 若有需要获取分类数据，可保留
  // fetchCategories();
});
</script>